import app from "./app";
import logger from "./utils/logger";
import { db } from "./config/database";
import oauthController from "./controller/oauthController";

const PORT = process.env.PORT || 8080;

async function startServe() {
    try {
        // 初始化数据库连接
        logger.info('🔄 正在初始化数据库连接...');
        await db.initialize();
        
        // 初始化OAuth控制器
        logger.info('🔄 正在初始化OAuth控制器...');
        await oauthController.initialize();
        
        // 数据库健康检查
        const healthStatus = await db.healthCheck();
        logger.info('📊 数据库健康状态:', healthStatus);

        const server = app.listen(PORT, () => {
            logger.info(`Server is running on port ${PORT}`);
        });

        const shutdown = async (signal: string) => {
            logger.info(`收到 ${signal} 信号，开始关闭...`);

            server.close(async () => {
                logger.info('HTTP 服务器已关闭');

                try {
                    // 关闭数据库连接
                    await db.disconnect();
                    logger.info('数据库连接已关闭');
                    process.exit(0);
                } catch (error) {
                    logger.error(`关闭数据库连接时出错:${error}`);
                    process.exit(1);
                }
            });

            // 如果 30 秒内无法优雅关闭，强制退出
            setTimeout(() => {
                logger.error('强制退出');
                process.exit(1);
            }, 30000);
        };
        
        // 监听退出信号
        process.on('SIGTERM', () => shutdown('SIGTERM'));
        process.on('SIGINT', () => shutdown('SIGINT'));

        // 未捕获异常处理
        process.on('uncaughtException', (error) => {
            logger.error(`未捕获的异常:${error}`);
            shutdown('uncaughtException');
        });

        process.on('unhandledRejection', (reason, promise) => {
            logger.error(`未处理的 Promise 拒绝:${reason}`);
            logger.error(`Promise:${promise}`);
            shutdown('unhandledRejection');
        });

    } catch (error) {
        logger.error(`startServe error:${error}`);
        process.exit(1);
    }
}

startServe();